package com.neurotech.pcc.ui.adapter

import android.os.Bundle
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.Navigation
import com.neurotech.pcc.R
import com.neurotech.pcc.dummy.AreaDevice
import com.neurotech.pcc.dummy.RemoteModel
import kotlinx.android.synthetic.main.fragment_scan_list.view.*
import java.util.*


/**
 * Created by shenhua on 2018/10/12.
 * @author shenhua
 */
class ScanItemAdapter : RecyclerView.Adapter<ScanItemAdapter.ViewHolder>() {

    private val datas = ArrayList<AreaDevice>()

    override fun getItemCount() = datas.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.fragment_scan_list, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val areaDevice = datas[position]
        holder.apply {
            bind(createOnClickListener(areaDevice), areaDevice)
        }
    }

    fun clear() {
        datas.clear()
        notifyDataSetChanged()
    }

    fun add(areaDevice: AreaDevice) {
        datas.add(areaDevice)
        notifyItemInserted(datas.size)
    }

    private fun createOnClickListener(areaDevice: AreaDevice): View.OnClickListener {
        return View.OnClickListener {
            val bundle = Bundle()
            val remoteModel = RemoteModel()
            remoteModel.host = areaDevice.ip
            remoteModel.port = "9"
            remoteModel.mac = areaDevice.mac
            bundle.putSerializable("remoteModel", remoteModel)
            Navigation.findNavController(it).navigate(R.id.action_scanFragment_to_configFragment, bundle)
        }
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bind(listener: View.OnClickListener, item: AreaDevice) {
            itemView.ipTv.text =
                    String.format(Locale.getDefault(), "%1\$s%2\$s", item.ip,
                            if (item.isLocal) itemView.context.getString(R.string.local_device) else "")
            itemView.macTv.text = item.mac
            itemView.setOnClickListener(listener)
        }
    }
}
